<template>
  <div class="cartwrapper">
    <PurchaseTips />
    <van-checkbox-group
      v-model="checkedArray"
      :disabled="isClicked"
    >
      <!-- 这个 disabled只是css层面的设置。。。有个锤子用。还是要在js那里设置-->
      <van-checkbox
        :name="item.product_id"
        class="goods_checkbox"
        v-for="item in cartList"
        :key="item.id"
        @click="onCheckBoxChange(item)"
      >
        <van-swipe-cell>
          <van-card
            :num="item.number"
            :price="item.market_price.toFixed(2)"
            :origin-price="item.retail_price.toFixed(2)"
            desc="描述信息"
            :title="item.goods_name"
            :thumb="item.list_pic_url"
          />
          <template #right>
            <van-button
              square
              text="删除"
              type="danger"
              class="delete-button"
              @click="handleDelete(item.product_id)"
            />
          </template>
        </van-swipe-cell>
        <van-stepper
          v-model="item.number"
          integer
          v-show="isClicked"
          @change="onStepperChange(item)"
        />
      </van-checkbox>
    </van-checkbox-group>

    <!-- 提交栏 -->
    <van-submit-bar
      :price="cartTotal.checkedGoodsAmount*100"
      button-text="提交订单"
      @submit="onSubmit"
    >
      <van-checkbox
        v-model="checkeAll"
        :disabled="cartTotal.goodsCount !== 0?isClicked:true"
      >全选</van-checkbox>
      <template #tip>
        累计共<span>{{cartTotal.goodsCount}}</span>件商品, 可点击 <van-button
          :type="isClicked?'danger':'primary'"
          size="mini"
          @click="isClicked=!isClicked"
        >{{isClicked?'完成':'编辑'}}</van-button> 按钮进行商品数量修改

      </template>
    </van-submit-bar>
  </div>
</template>

<script>
import PurchaseTips from "@/components/PurchaseTips.vue";
import {
  GetCartData,
  RefreshCartData_checkbox,
  RefreshCartData_stepper,
  DeleteGood,
} from "@/request/api";
export default {
  data() {
    return {
      //选中的checkbox的name属性数组
      checkedArray: [],
      //购物车数据
      cartList: [],
      //购物车数值信息
      cartTotal: [],
      //编辑按钮是否被点击、步进器是否显示、复选框disabled状态
      isClicked: false,
    };
  },
  computed: {
    //提交订单栏全选checkbox状态改变，请求更新购物车数据
    checkeAll: {
      get() {
        return this.checkedArray.length == this.cartList.length;
      },
      async set(newVal) {
        // console.log(newVal);
        if (this.isClicked) {
          return;
        } else {
          if (this.cartList.length == 0) return;
          let arr = [];
          this.cartList.forEach((element) => {
            arr.push(element.product_id);
          });
          let res = await RefreshCartData_checkbox({
            isChecked: newVal ? 1 : 0,
            productIds: arr.join(),
          });
          console.log(res);
          if (res.errno !== 0) return this.$toast.fail("修改失败！");
          this.handleCartData(res.data);
        }
      },
    },
  },
  components: { PurchaseTips },

  async created() {
    //获取购物车数据
    let res = await GetCartData();
    console.log("created购物车数据", res);
    if (res.errno !== 0) return this.$toast.fail("获取购物车数据失败！");
    this.handleCartData(res.data);
  },

  methods: {
    //处理渲染购物车数据
    handleCartData(data) {
      let { cartList, cartTotal } = data;
      this.cartList = cartList;
      this.cartTotal = cartTotal;
      //每次渲染前，先重置数组
      this.checkedArray = [];
      //将用户购物车里checked的商品唯一标识给存入checkbox双向绑定的数组进行渲染
      cartList.forEach((element) => {
        if (element.checked == 1) {
          //只要标识唯一就行，本来用goods_id，但后面考虑到其它请求发送要拼接product_id为参数
          this.checkedArray.push(element.product_id);
        }
      });
    },
    //checkbox点击事件处理函数（单选）
    async onCheckBoxChange(item) {
      //编辑按钮是否被点击，是则直接return不发送请求
      if (this.isClicked) {
        return;
      } else {
        let res = await RefreshCartData_checkbox({
          isChecked: item.checked == 1 ? 0 : 1,
          productIds: item.product_id,
        });
        // console.log(res);
        if (res.errno !== 0) return this.$toast.fail("修改失败！");
        this.handleCartData(res.data);
      }
    },
    //步进器状态改变，更新购物车选中数据。
    async onStepperChange(item) {
      console.log(item);
      let res = await RefreshCartData_stepper({
        goodsId: item.goods_id,
        id: item.id,
        number: item.number,
        productId: item.product_id,
      });
      console.log(res);
      if (res.errno !== 0) return this.$toast.fail("修改失败！");

      this.handleCartData(res.data);
    },
    //删除商品按钮
    async handleDelete(product_id) {
      //注意请求需要字符串形式的参数！
      let res = await DeleteGood({ productIds: product_id.toString() }).catch(
        (err) => err
      );
      // console.log(res);
      if (res.errno !== 0)
        return this.$toast.fail(
          res.errmsg !== "" ? res.errmsg : false || "删除失败！"
        );
      this.$toast.success("删除成功！");
      this.handleCartData(res.data);
    },
    //提交订单
    onSubmit() {
      this.$toast.success("已提交！。。。没有支付功能");
    },
  },
};
</script>

<style lang='less' scoped>
.van-submit-bar {
  bottom: 0.5rem;
  .van-submit-bar__tip {
    display: flex;
    align-items: center;
    .van-button {
      margin: 0 0.02rem;
    }
  }
}
//商品多选框
.van-checkbox-group {
  // margin: 0 0.1rem;
  padding: 0.1rem;
  background-color: #fff;
}
.goods_checkbox {
  padding: 0.1rem;
  //1px边框
  position: relative;
  &::after {
    content: "";
    position: absolute;
    left: 0;
    bottom: 0;
    height: 5px;
    border-bottom: 1px solid #000;
    transform-origin: 0;
    @media (max--moz-device-pixel-ratio: 1.49),
      (-webkit-max-device-pixel-ratio: 1.49),
      (max-device-pixel-ratio: 1.49),
      (max-resolution: 143dpi),
      (max-resolution: 1.49dppx) {
      width: 100%;
    }
    @media (min--moz-device-pixel-ratio: 1.5) and (max--moz-device-pixel-ratio: 2.49),
      (-webkit-min-device-pixel-ratio: 1.5) and (-webkit-max-device-pixel-ratio: 2.49),
      (min-device-pixel-ratio: 1.5) and (max-device-pixel-ratio: 2.49),
      (min-resolution: 144dpi) and (max-resolution: 239dpi),
      (min-resolution: 1.5dppx) and (max-resolution: 2.49dppx) {
      width: 200%;
      transform: scale(0.5);
    }
    @media (min--moz-device-pixel-ratio: 2.5),
      (-webkit-min-device-pixel-ratio: 2.5),
      (min-device-pixel-ratio: 2.5),
      (min-resolution: 240dpi),
      (min-resolution: 2.5dppx) {
      width: 300%;
      transform: scale(0.333333);
    }
  }
  /deep/ .van-checkbox__label {
    flex: 1;
    // width: 100%;
    .van-card {
      background-color: #fff;
    }
  }
}
//步进器
.van-stepper {
  text-align: right;
}
//删除商品按钮
.delete-button {
  height: 100%;
}
</style>